import requests
import time
import os
from playsound import playsound

# 替换为你的百度API Key和Secret Key
API_KEY = 'RS30gmExFxCK9rF4rWpqmg3b'
SECRET_KEY = 'MW4XC2Z1xOJTT4fc1ZEOEQicraAMWnAG'
# 青蛙 买卖 泉水
def get_token(api_key, secret_key):
    url = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()['access_token']
    else:
        raise Exception("Cannot obtain token from Baidu API")

def text_to_speech(text, token):
    tts_url = 'https://tsn.baidu.com/text2audio'
    params = {
        'tex': text,
        'tok': token,
        'cuid': 'cRzJP0kwkNM5RU1BuNpfxSwMJ5gIXxA5',
        'ctp': 1,
        'lan': 'zh',
        'aue': 6,  # MP3
    }
    response = requests.post(tts_url, data=params)
    if response.headers['Content-Type'] == 'audio/mp3':
        filename = f"{text}.mp3"
        with open(filename, 'wb') as f:
            f.write(response.content)
        return filename
    else:
        raise Exception("Error in TTS API call")

if __name__ == "__main__":
    words = input("请输入几个词语（用空格分隔）：")
    token = get_token(API_KEY, SECRET_KEY)

    for word in words.split():
        audio_file = text_to_speech(word, token)
        for _ in range(3):  # 每个词读三遍
            playsound(audio_file)
            time.sleep(3)  # 每遍之间间隔3秒
        os.remove(audio_file)  # 删除临时音频文件
